package com.game.league.task.detail.panel;

import android.app.Activity;
import android.text.TextUtils;
import android.view.View;

import androidx.recyclerview.widget.GridLayoutManager;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import com.game.base.app.base.BasePanel;
import com.game.base.app.callback.ItemOnClick;
import com.game.base.camera.ImgSelectUtil;
import com.game.base.server.file.qiniulibrary.QiniuiCloudMgr;
import com.game.base.server.file.qiniulibrary.UploadType;
import com.game.base.server.file.qiniulibrary.listener.QiniuUploadMutliListener;
import com.game.base.utils.toast.ToastUtil;
import com.game.base.view.dialog.DialogUtils;
import com.game.league.R;
import com.game.league.databinding.PanelTaskSubmitBinding;
import com.game.league.service.InterfaceMgr;
import com.game.league.task.detail.TaskDetailActivity;
import com.game.league.task.detail.adapter.ExampleImgAdapter;
import com.game.league.task.detail.adapter.UploadImgAdapter;
import com.game.league.task.table.MyTask;
import com.game.league.task.table.Task;
import com.game.league.util.SkipUtil;

import java.util.ArrayList;
import java.util.List;

import cn.bmob.v3.exception.BmobException;
import cn.bmob.v3.listener.SaveListener;

/**
 * 提交
 * Created by Su on 2019/6/7.
 */
public class SubmitPanel extends BasePanel<PanelTaskSubmitBinding> implements ItemOnClick, View.OnClickListener {
    private ExampleImgAdapter imgAdapter;
    private List<String> imgList, uploadList;  //图片数据
    private UploadImgAdapter uploadAdapter;

    private Task task = SkipUtil.currentTask;

    @Override
    protected int getLayoutId() {
        return R.layout.panel_task_submit;
    }

    public SubmitPanel(Activity activity) {
        super(activity);
        initView();
    }

    private void initView() {
        binding.setClick(this);

        LinearLayoutManager exampleManager = new LinearLayoutManager(activity);
        exampleManager.setOrientation(RecyclerView.HORIZONTAL);
        binding.recyclerSubExample.setLayoutManager(exampleManager);
        imgAdapter = new ExampleImgAdapter(activity, 2, this);
        binding.recyclerSubExample.setAdapter(imgAdapter);

        uploadList = new ArrayList<>();
        binding.recyclerSubUpload.setLayoutManager(new GridLayoutManager(activity, 4));
        uploadAdapter = new UploadImgAdapter(activity, (viewId, position, o) -> handleUpload(position));
        binding.recyclerSubUpload.setAdapter(uploadAdapter);
    }

    public void refreshData() {
        if (task.getExampleImg() == null || task.getExampleImg().isEmpty()) {
            binding.recyclerSubExample.setVisibility(View.GONE);
            binding.recyclerSubUpload.setVisibility(View.GONE);
        } else {
            // 示例图
            imgList = task.getExampleImg();
            imgAdapter.setItems((ArrayList<String>) imgList);

            // 上传图
            for (int i = 0; i < imgList.size(); i++) {
                uploadList.add("");
            }
            uploadAdapter.setItems((ArrayList<String>) uploadList);
        }
    }

    private void handleUpload(int position) {
        ImgSelectUtil.getInstance().pickPhoto(activity, url -> {
            uploadList.set(position, url);
            uploadAdapter.notifyItemChanged(position);
        });
    }

    @Override
    public void onItemClick(int viewId, int position, Object o) {
        SkipUtil.showBigImgPreview(activity, position, imgList);
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.btn_submit:
                DialogUtils.showMessagePositiveDialog(activity, "注意",
                        "请确认是否严格按照要求完成任务，流程错误可能会造成审核失败哦！", (dialog, index) -> submit());
                break;
        }
    }

    private void submit() {
        if (task == null) {
            ToastUtil.showShort("数据异常，请退出重试");
            return;
        }
        DialogUtils.showLoadingDialog(activity, "提交中...");
        QiniuiCloudMgr.getInstance().uploadMutliFiles(uploadList, UploadType.UPLOAD_TASK, new QiniuUploadMutliListener() {
            @Override
            public void onUploadMutliSuccess(List<String> urlList) {
                submitTask(urlList);
            }

            @Override
            public void onUploadMutliFail() {
                DialogUtils.closeTipDialog();
                ToastUtil.showLong("部分截图上传失败，请重试");
            }

            @Override
            public void onUploadEmpty() {
                submitTask(new ArrayList<>());
            }
        });
    }

    private void submitTask(List<String> auditImg) {
        MyTask myTask = new MyTask();
        myTask.setTask(task);
        myTask.setAuditImg(auditImg);
        myTask.setPrice(task.getPrice());

        String signName = binding.tvSignName.getText().toString();
        if (!TextUtils.isEmpty(signName)) {
            myTask.setSignName(signName);
        }

        String signPhone = binding.tvSignPhone.getText().toString();
        if (!TextUtils.isEmpty(signPhone)) {
            myTask.setSignPhone(signPhone);
        }

        InterfaceMgr.getInstance().submitTask(myTask, new SaveListener<String>() {
            @Override
            public void done(String s, BmobException e) {
                DialogUtils.closeTipDialog();
                ((TaskDetailActivity) getActivity()).isStartTask = false;
                binding.btnSubmit.postDelayed(() -> ToastUtil.showShort(e == null ? "提交成功" : "提交失败"), 300);
            }
        });
    }
}
